package com.nowcoder.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class ServiceLogAspect {//Spring中存在XXXAutoConfiguration，里面有@Bean注解的方法


    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointcut(){ }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint){//JoinPoint：切入到某个方法中的连接点
        //用户 [ip(xxx.xxx.xxx.xxx)] 在 [当前时刻] 访问了 [方法名称]
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        //消费者调用时可能会出现attributes为null的情况
        if (attributes == null){
            return;
        }

        //获取当前请求
        HttpServletRequest request = attributes.getRequest();
        //获取当前请求的主机ip地址
        String ip = request.getRemoteHost();
        //获取当前时刻
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //获取目标方法名（切入点）
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();

        logger.info(String.format("用户[%s]，在[%s]，访问了[%s].", ip, now, target));
    }

    @After("pointcut()")
    public void after(){
//        System.out.println("after");
    }

    @AfterReturning("pointcut()")
    public void afterReturning(){
//        System.out.println("afterReturning");
    }

    @AfterThrowing("pointcut()")
    public void afterThrowing(){
//        System.out.println("afterReturning");
    }

    /*@Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("around before");
        Object obj = joinPoint.proceed();
        System.out.println("around after");

        return obj;
    }*/
}
